# 小程序

## lib.js

1. andy-aui/lib/global
2. 支持 `Promise.prototype.finally` 
3. 支持 `Object.values`
4. 支持 `Array.prototype.includes`
5. 支持 `Object.entries`
6. 支持 `String.prototype.padStart`
7. 支持 `String.prototype.padEnd`

## reset

### button

```scss
.a-btn {
    padding: 0;
    margin: 0;
    border-radius: 0;
    text-align: left;
    line-height: 1;
    &:after {
        border-radius: 0;
        border: none;
        background-color: transparent;
    }
}
```

### input

```scss
.a-input {
    height: 1.4em;
    min-height: 1.4em;
    font-size: 1em;
    line-height: 1.5;
}
```

### navigator

navigator-hover的时候有莫名其妙的背景色

https://developers.weixin.qq.com/miniprogram/dev/component/navigator.html



## 样式

<a href="#/basic/sass" target="__blank">sass mixin</a>

<a href="#/basic/README" target="__blank">common css</a>

## app

app.js 的插件

### collect.js

用来收集用户userinfo的 和 小程序getUserInfo button联动

### formid.js

用于提供formid的

## common

### wxs

#### index.wxs
#### date.wxs

##### format

### app.js

#### getAppName

得到AppName

### auth.js

#### getGlobalServerInfo

得到登陆的用户信息

#### loginServer

登陆小程序后台

### net.js

#### NetService

#### pagination service

处理某一类分页通用类

```javascript
let service = new class extends PaginationNetService {
    constructor() {
        super({
            request(curPageNum, pageSize, rqd) {
            },
            response(data, isFirst) {
            }
        })
    }
};
```

### wx.js

简化wx全局api调用
大部分api promise化

#### promised

##### scanCode 
##### previewImage
##### getImageInfo
##### saveImageToPhotosAlbum
##### chooseVideo
##### saveVideoToPhotosAlbum
##### chooseImage
##### getFileInfo
##### getSavedFileList
##### getSavedFileInfo
##### removeSavedFile
##### openDocument
##### getLocation
##### chooseLocation
##### openLocation
##### getNetworkType
##### setClipboardData
##### getClipboardData
##### setScreenBrightness
##### getScreenBrightness
##### keepScreenOn
##### addPhoneContact
##### showLoading
##### setNavigationBarTitle
##### setTabBarBadge
##### removeTabBarBadge
##### showTabBarRedDot
##### hideTabBarRedDot
##### setTabBarStyle
##### setTabBarItem
##### showTabBar
##### hideTabBar
##### requestPayment
##### showToast
##### hideToast
##### hideLoading

#### fun
##### showNavigationBarLoading
##### hideNavigationBarLoading
##### makePhoneCall

#### context
##### createMapContext
##### createLivePusherContext
##### createLivePlayerContext
##### createCameraContext 
##### createVideoContext

#### manager
##### getRecorderManager
##### getBackgroundAudioManager

#### custom
##### updateApp
##### navigateTo
设置storage __curUrl
##### redirectTo
设置storage __curUrl
##### changeTo
```
changeTo(url, true) // use redirectTo
changeTo(url, false) // use navigateTo
```
##### changeToPage

##### switchTab
设置storage __curUrl
##### navigateBack
##### reLaunch
##### getCurUrl
##### initWx
在app.js中初始化代码


##### uploadFile(url, filePath, onSend: Function, formData: Object)
##### downloadFile(url, filePath, onSend: Function)

##### setNavBarTitle(title)
##### stopPullDownRefresh()
##### showPageLoading(text = "加载中")

##### setStorageSync(k, v)
##### getStorageSync
##### getStorageInfoSync()
##### removeStorageSync(k)
##### clearStorageSync

##### getSystemInfoSync

##### startAccelerometer
##### stopAccelerometer

##### hidePageLoading
##### pageScrollTo(d, duration = 300) 
##### showModal(title, content)


重新搜索

```javascript
fuckService.resetSearch([requestData]);
```

处理attachBottom
```javascript
fuckService.handleBeachBottom(()=> {
    // onstart
}, ()=> {
    // onSuccess
})
```

## vendors (v2)

### moka 2.0.1

#### arr.js

##### isEmpty
判断数组是否为空

#### auth.js

##### requestAuth

```javascript
requestAuth("scope.userLocation", "请给与location授权")
    .then(function () {
        showToast({
            title: "location已授权"
        })
    })
    .catch(function (e) {
        showToast({
            title: "location未授权"
        })
    })
```

##### checkHasAuth
##### authLogin

请求用户允许 

#### date.js

##### isAfter
##### isBefore
##### isEqual
##### max
##### min
##### parse
##### getTime
##### isThisHour
##### isThisQuarter
##### isThisWeek
##### isThisMonth
##### isThisYear
https://date-fns.org/docs/Getting-Started

##### getAMPM
判断是是AM还是PM

#### db.js

localstorage db

```javascript
let db = new LocalStorageDB("played", MLocalStorage);
if (!db.tableExists(tableName)) {
    db.createTableIfNotExists(tableName, ["a"]);
    db.insert(tableName, {
        a: 1
    });
} else {
    db.dropTable(tableName);
}
db.commit();
```

##### methods

1. tableExists
2. createTableIfNotExists
3. insert
4. dropTable
5. commit

#### http.js

##### post
##### get

#### lodash.js

lodash 的一些方法

```javascript
/**
* _.assignIn, _.before, _.bind, _.chain, _.clone, _.compact, _.concat, 
* _.create, _.defaults, _.defer, _.delay, _.each, _.escape, _.every, 
* _.filter, _.find, _.flatten, _.flattenDeep, _.forEach, _.has, _.head, 
* _.identity, _.indexOf, _.isArguments, _.isArray, _.isBoolean, _.isDate,
*  _.isEmpty, _.isEqual, _.isFinite, _.isFunction, _.isNaN, _.isNull, 
* _.isNumber, _.isObject, _.isRegExp, _.isString, _.isUndefined, _.iteratee, 
* _.keys, _.last, _.map, _.matches, _.max, _.min, _.mixin, _.negate,
*  _.noConflict, _.noop, _.once, _.pick, _.reduce, _.result, _.size, _.slice,
*  _.some, _.sortBy, _.tap, _.thru, _.toArray, _.uniqueId, _#value, & _.values
*
*  extend
*  _.defaultTo
*/
```

#### md5.js

md5 加密

#### net.js 

#### storage.js 

##### storage

微信 storage 的保持

```javascript
let storage = new Storage(wx);
```

set
```javascript
storage.set('userinfo',{
  username: 'axetroy',
  age: 'Forever Young'
});
```

```javascript
// 设置过期时间
storage.set('userinfo',{
    username: 'axetroy',
    age: 'Forever Young'
}, 1000);
```

get
```javascript
console.log(storage.get('userinfo'));
```

remove
```javascript
storage.remove('userinfo');
```

##### MLocalStorage

类似浏览器localStorage的全局对象

#### tpl.js 

##### template

解析str模板

```javascript
template(`sdsd{sds}`, {
    sds: 1
});
```

#### unit.js

用于canvas单位

#### utils.js

##### deepSet
##### deepGet
##### getByPath
##### debounce
##### throttle


## npm.js

### utils[node]

使用aui node模式 utils

### lodash
```javascript
/**
 * _.assignIn, _.before, _.bind, _.chain, _.clone, _.compact, _.concat, 
 * _.create, _.defaults, _.defer, _.delay, _.each, _.escape, _.every, 
 * _.filter, _.find, _.flatten, _.flattenDeep, _.forEach, _.has, _.head, 
 * _.identity, _.indexOf, _.isArguments, _.isArray, _.isBoolean, _.isDate,
 *  _.isEmpty, _.isEqual, _.isFinite, _.isFunction, _.isNaN, _.isNull, 
 * _.isNumber, _.isObject, _.isRegExp, _.isString, _.isUndefined, _.iteratee, 
 * _.keys, _.last, _.map, _.matches, _.max, _.min, _.mixin, _.negate,
 *  _.noConflict, _.noop, _.once, _.pick, _.reduce, _.result, _.size, _.slice,
 *  _.some, _.sortBy, _.tap, _.thru, _.toArray, _.uniqueId, _#value, & _.values
 *
 *  extend
 *  _.defaultTo
 */
```

### Fuse

javascript 搜索引擎

http://fusejs.io/



### date

[mokav2.date](#date)

### validator

@select

https://github.com/chriso/validator.js

## dev.js

### npm

[npm.js](#npm-js)

### utils

使用[aui.utils](\#/api/README?id=utils-%E9%BB%98%E8%AE%A4)

### template

use [moka@2.0.1 tpl](#tpl-js)

### debounce

```javascript
let dec = debounce((arg)=> {
    
}, 1000, true)
```

### compareVersion

```javascript
function compareVersion(v1, v2) {
  v1 = v1.split('.')
  v2 = v2.split('.')
  var len = Math.max(v1.length, v2.length)

  while (v1.length < len) {
    v1.push('0')
  }
  while (v2.length < len) {
    v2.push('0')
  }

  for (var i = 0; i < len; i++) {
    var num1 = parseInt(v1[i])
    var num2 = parseInt(v2[i])

    if (num1 > num2) {
      return 1
    } else if (num1 < num2) {
      return -1
    }
  }

  return 0
}

// compareVersion('1.9.91', '2.0.6')  -> -1
// compareVersion('2.0.6', '2.0.6')  -> 0
// compareVersion('2.0.7', '2.0.6')  -> 1
```

## base.js

BaseCom

### props

#### ref

refs中每一个都是一个component的id 

page 可以在onLoad 中获取到其实例

```javascript
refs = [
    "menus",
    "popup"
];
```

### data

#### $sys

可以在context上获得 $sys getSystemInfoSync()

### methods

#### _getComponentById
selectComponent的简便版本
#### _setByKey
setData 的key, value版本

#### $buildUrl(url)
#### $toast(title = '', opt = {})
#### $toggleLoading(show) 

#### $getSettingByKey(key)
```javascript
try {
    let isHas = await self.$getSettingByKey('scope.userInfo');
    console.log(isHas);
} catch (e) {
    console.error('_attached $getSettingByKey', e);
}
```
#### $setDataTrueIfOldIsFase
#### $getShareAppMessage(title, path, opt = {imageUrl: ''})
返回shareAppMessage
#### $template

## pages

```
---- page1
---------- index.js
---------- index.json
---------- index.axml
```

### v2page.js

#### props

#### $opt
#### $routeinfo 

当当前页面栈大于一个的时候  得到上一个页面
```javascript
{
    fromPage // 
    fromRoute  //
    fromRouteInfo  //
}
```

```javascript
import {BaseCom} from "../v2base";

export function mPage(mix) {
    let _def = new BaseCom();
    let def = Object.assign(_def.methods, _def.data, _def.properties, mix);
    Page(def);
}
```

### page.js

page 继承 BaseCom

```javascript
let op;
let p = new class extends MPage {
    onLoad(options) {
        super.onLoad(options);
        op = options;
    }
};

Page(BindMPage(p));
```

#### 扩充 page

##### _currentPages
##### _pagesInfo

当当前页面栈大于一个的时候  得到上一个页面
```
{
    fromPage // 
    fromRoute  //
    fromRouteInfo  //
}
```

#### attrs

##### _routeinfo
得到每个页面的当前route信息

```javascript
{
    route: "",
    query: {},
    loadUrl: ""
}
```

#### props

##### $opt
onload 时候的参数
##### $data
##### $context

#### data
data 会被编译到 data 上

## page.axml

所有页面共用的功能

可以使用page.twig  [common/index.wxs](#common)

## page.twig

## page.wxsc

所有页面共用的样式

## components (v1)

### mads
mads 解决广告的问题

### navi

```xml
<a-navi
    app="{{}}"
    app-id="{{}}"
    app-path="{{}}">
    <view slot="content">
        <!-- 非app跳转 -->
    </view>
    <view slot="app">
        <!-- app跳转 -->
    </view>
</a-navi>
```

灵活跳app或者app内部操作

### storagecheck

#### props

##### key: String

通过检测storage中是否有某个key值来判断

## components (v2)

```
--- *.behavior.js
--- com.js
--- com.wxsc           // 组件的公共样式
--- com.axml
--- com.twis
--- listview.twis
--- com/               // 组件之间共享的文件
--- coma/
-------- index.js
-------- index.json
-------- index.wxml
-------- index.wxss
-------- lib.wxsc
```

### com.js

### props
#### refs

支持refs  

attached 的时候就可以使用了

#### MComponent

```javascript
let c = new class extends MComponent {

}

Component(c);
```

#### MMultiComponent



### field
input框

### select [plain]
### select-trigger [plain]

### guide 
引导
### image 
<p class="warning">只能使用网络图片</p>

### item
item

### pick

选择显示某个slot

#### props

##### len

需要插入slot个数

### popup

依赖zanui popup

#### event

##### uiclose

当ui关闭时

#### method

##### show
##### close
##### enable
打开点击overlay关闭
```javascript
popup.enable({
    overlayClose: true
})
```

### text

自动overflow

```xml
<text>long text</text>
```

#### props

##### line: Number

设置line可以实现多行

### baseview.behavior

### listview
listview

### listview.bahavior

```javascript
const listviewBehavior = require("../listview.behavior")();
```

### menus
横向tab
### tabnav.bahavior

```javascript
let tabnavBehvior = require("../tabnav.bahavior")();
```

#### event
##### itemtap

当每一个item被点击时触发

#### methods
##### set(v: Array)
设置渲染的数据

##### setIndex(index, v)
##### setActive(index)
##### getActiveIndex
##### getActiveItem

### user 

自动加载user的数据

低版本展现登录按钮

### user.behavior

```javascript
let userBehavior = require("../user.behavior")();
```

自动加载用户数据

会在storage里留下一个自定义storageName的row

### pick

用于选择某个item元素展示  

如果子元素和picK 元素通过 `pickItem.behavior.js` 关联  当元素被选中时就会触发 `onSelect` 上一个关联元素会触发 `onUnSelect`

#### events

##### activeitem
激活某个元素时

##### itemnofind
当设置的active index合法但没有发现相应Item时

#### methods

##### getActiveItem
##### setActive

## vendors (others)

### mta
腾讯分析
### ad
广告
### zan
zan ui

## 页面布局

### 左右居中 column

prefix: wx-a-column

```xml
<view class="u-list u-layout-flex vertical center">
    <view class="u-list__item">$1$</view>
</view>
```

### 最普通的column 和一张image

prefix: wx-a-column-img

```xml
<view class="u-list u-layout-flex vertical center">
    <image class="u-list__item" 
        style="width: 40rpx; height: 40rpx;"
        src="$1$"
    ></image>
    <view class="u-list__item">$2$</view>
</view>
```

### scroll view 横向

prefix: wx-a-s-hlist

```xml
<scroll-view class="u-list u-list--h exp-hlist" scroll-x>
    <view class="u-list-item exp-hlist__item" wx:for="{{10}}" wx:key="*this">{{item}}</view>
</scroll-view>
```

### scroll view 纵向

prefix: wx-a-s-vlist

```xml
<scroll-view class="u-list exp-vlist"  scroll-y>
    <view class="u-list-item exp-vlist__item" wx:for="{{10}}" wx:key="*this">{{item}}</view>
</scroll-view>
```

### 最常见左右列表

prefix: wx-a-hlist

```xml
<view class="u-list u-layout-flex horizontal a-hlist $1$">
    <view class="u-list-item a-hlist__item $1$__item">left</view>
    <view class="u-list-item a-hlist__item $1$__item full">right</view>
</view>
```

### 最常见上下列表

prefix: wx-a-vlist

```xml
<view class="u-list u-layout-flex vertical a-vlist $1$">
    <view class="u-list-item a-vlist__item $1$__item">top</view>
    <view class="u-list-item a-vlist__item $1$__item full">bottom</view>
</view>
```

### grid

prefix: wx-a-grid

```xml
<view class="u-list u-layout-flex horizontal wrap a-grid $1$">
    <view class="u-list-item a-grid__item $1$__item" 
        wx:for="{{10}}" wx:key="*this">{{item}}</view>
</view>
```

### swiper

prefix: wx-swiper

```xml
<swiper
        class="a-index-swiper"
        indicator-color="{{$1$.indicatorColor}}"
        indicator-active-color="{{$1$.indicatorActiveColor}}"
        indicator-dots="{{$1$.indicatorDots}}"
        circular="{{$1$.circular}}"
        autoplay="{{$1$.autoplay}}"
        interval="{{$1$.interval}}"
        duration="{{$1$.duration}}">
    <block
            wx:for="{{$2$}}"
            wx:key="{{item.rid}}"
        >
        <swiper-item>
            $3$
        </swiper-item>
    </block>
</swiper>
```

js部分使用 

```javascript
let banner = createSwiper(

);
```

默认配置 

```javascript
{
    indicatorDots: true,
    autoplay: true,
    interval: 4000,
    duration: 1000,
    circular: true,
    ["indicatorColor"]: "#999999",
    ["indicatorActiveColor"]: "#ffffff",
}
```